package com.my.test.img;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.imageio.ImageIO;

public class ImageMarker {
	// 水印透明度
    private float alpha = 0.5f;
    // 水印文字字体
    private Font font = new Font("宋体", Font.BOLD, 40);
    // 水印文字颜色
    private Color color = Color.red;
    //水印位置
    private MarkerPosition position = MarkerPositions.CENTER ;
    
    /**
     * 给图片添加水印图片、可设置水印图片旋转角度
     *
     * @param iconPath
     *            水印图片路径
     * @param srcImgPath
     *            源图片路径
     * @param targerPath
     *            目标图片路径
     */
    public void markByIcon(String iconPath, String srcImgPath,
                                       String targerPath) {
        Date start = new Date();
        OutputStream os = null;
        InputStream is;
        Image srcImg;
        try {

            //本地
            is = new FileInputStream(new File(srcImgPath)) ;
            		
            srcImg = ImageIO.read(is);

            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
                    srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);

            // 1、得到画笔对象
            Graphics2D g = buffImg.createGraphics();

            // 2、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);

            g.drawImage(
                    srcImg.getScaledInstance(srcImg.getWidth(null),
                            srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0,
                    null);
            

            // 4、水印图片的路径 水印图片一般为gif或者png的，这样可设置透明度
            // 5、得到Image对象。
            Image img = ImageIO.read(new FileInputStream(new File(iconPath)));
            // 6、水印图片的位置

            ImagePoint point = position.calculate(srcImg.getWidth(null), srcImg.getHeight(null)
            		, img.getWidth(null), img.getHeight(null)
            		, 0, 0, 0, 0);
           
            g.drawImage(img, point.x, point.y, null);
            // 7、释放资源
            g.dispose();

            // 8、生成图片
            os = new FileOutputStream(targerPath);
            ImageIO.write(buffImg, "JPG", os);
            Date end = new Date();
            System.out.println("图片完成添加水印图片");
            System.out.println("处理时间:"+(end.getTime()-start.getTime())/1000+"秒");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给图片添加水印文字
     *
     * @param logoText
     *            水印文字
     * @param srcImgPath
     *            源图片路径
     * @param targerPath
     *            目标图片路径
     */
    public void markByText(String logoText, String srcImgPath,
                                       String targerPath) {
        markByText(logoText, srcImgPath, targerPath, false);
    }

    /**
     * 给图片添加水印文字、可设置水印文字的旋转角度
     *
     * @param logoText
     * @param srcImgPath
     * @param targerPath
     * @param degree
     */
    public void markByText(String logoText, String srcImgPath,
                                       String targerPath, boolean isRotat) {

        InputStream is = null;
        OutputStream os = null;
        try {
            // 1、源图片
            Image srcImg = ImageIO.read(new File(srcImgPath));
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
                    srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);

            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(
                    srcImg.getScaledInstance(srcImg.getWidth(null),
                            srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0,
                    null);
            
            // 5、设置水印文字颜色
            g.setColor(color);
            // 6、设置水印文字Font
            g.setFont(font);
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));
            // 8、第一参数->设置的内容，后面两个参数->文字在图片上的坐标位置(x,y)
            FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
            int logoBlockHeight = fm.getHeight() ;
            int logoBlockWidth = fm.stringWidth(logoText) ;
            ImagePoint point = position.calculate(srcImg.getWidth(null), srcImg.getHeight(null)
            		, logoBlockWidth, logoBlockHeight
            		, 0, 0, 0, 0);
         // 4、设置水印旋转
            if (isRotat) {
        			int y1 = (int) ((1-Math.cos(45))*logoBlockWidth) ;
        			point.x = point.x+y1/2 ;
        			point.y = point.y+y1/2 ;
                g.rotate(Math.toRadians(-45),point.x, point.y);
            }
            g.drawString(logoText, point.x, point.y);
            // 9、释放资源
            g.dispose();
            // 10、生成图片
            os = new FileOutputStream(targerPath);
            ImageIO.write(buffImg, "jpg", os);
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is)
                    is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取实例
     * @return
     */
    public static ImageMarker get() {
		return new ImageMarker() ;
	}
    /**
     * 水印透明度
     * @param alpha
     * @return
     */
    public ImageMarker setAlpha(float alpha) {
		this.alpha = alpha;
		return this ;
	}


	/**
	 * 水印文字字体
	 * @param font
	 * @return
	 */
	public ImageMarker setFont(Font font) {
		this.font = font;
		return this ;
	}

	/**
	 * 水印文字颜色
	 * @param color
	 * @return
	 */
	public ImageMarker setColor(Color color) {
		this.color = color;
		return this ;
	}

	public ImageMarker setPosition(MarkerPosition position) {
		this.position = position;
		return this ;
	}

	public static void main(String[] args) {
        
        String srcImgPath = "/Users/zongbo/Pictures/abc.jpg";
        String logoText = "ctitc deep";
        String iconPath = "/Users/zongbo/Pictures/search.jpg";

        String targerTextPath = "/Users/zongbo/Pictures/ccc111.png";

        String targerIconPath = "/Users/zongbo/Pictures/ccc2222.png";

        System.out.println("给图片添加水印文字开始...");
        ImageMarker marker = ImageMarker.get().setAlpha(0.5f).setColor(Color.white).setPosition(MarkerPositions.BOTTOM_RIGHT) ;
        // 给图片添加水印文字,水印文字旋转-45
        marker.markByText(logoText, srcImgPath, targerTextPath);
        System.out.println("给图片添加水印文字结束...");

//        System.out.println("给图片添加水印图片开始...");
//        // 给图片添加水印图片,水印图片旋转-45
//        marker.markByIcon(iconPath, srcImgPath, targerIconPath);
//        System.out.println("给图片添加水印图片结束...");
    }
}
